package org.example.struct.array;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyishan
 * @date 2023/7/31 13:08
 * @apiNote
 */

public class Test00169MajorityElement {
    public static void main(String[] args) {
        int[] a = new int[]{1, -1, 1, -1, 1, -1,1};
        int count = test3(a);
        System.out.println(count + "  array:" + JSON.toJSON(a));
    }


    public static int test1(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(!map.containsKey(nums[i])){
                map.put(nums[i],1);
            }else{
                map.put(nums[i],map.get(nums[i])+1);
            }
        }
        for(Map.Entry<Integer,Integer> enrty:map.entrySet()){
            if(enrty.getValue()>nums.length/2){
                return enrty.getKey();
            }
        }
        return -1;
    }

    public static int test2(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }

    public static int test3(int[] nums) {
        int count = 0;
        Integer candidate = null;
        for(int num:nums){
            if(count == 0){
                candidate = num;
            }
            count += (num == candidate) ? 1:-1;
        }
        return candidate;
    }
}
